package ld.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: Liudao
 * @Date: 2022-07-27-15:35
 * @Description:
 */

public class MyBatisUtil {

    //1. 得到sqlSessionFactory
    private static SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "config/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

    //2. 得到sqlsession对象
    public static SqlSession getSqlSession(){
        SqlSessionFactory sqlSessionFactory = null;
        try {
            sqlSessionFactory = getSqlSessionFactory();
            return sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

